const app = getApp()

export function request(params) {
    // 初始化参数
    let urlIsAll = params.urlIsAll;
    let url = app.DOMAIN_NAME + params.url;
    if (urlIsAll) {
        url = params.url;
    } else {
        url = app.DOMAIN_NAME + params.url;
    }
    let header = params.header || {};
    let data = params.data || {};
    let method = params.method || "GET";
    // 初始化数据
    header["content-type"] = 'application/json';
    if (wx.getStorageSync('token')) {
        header["Authorization"] = 'Bearer ' + wx.getStorageSync('token');
    }
    if (wx.getStorageSync('parkId')) {
        data.parkId = wx.getStorageSync('parkId')
    }

    // 加载中
    wx.showLoading({
        mask: true,
        title: '正在加载..'
    })
    // 创建请求
    return new Promise((resolve, reject) => {
        wx.request({
            url,
            method,
            data,
            header,
            success: res => {
                // 加载完成
                wx.hideLoading()
                // 身份信息过期
                if (res.data.code == 402 || res.data.code == 401) {
                    wx.showModal({
                        confirmText: '确认',
                        content: '身份已过期,需重登录',
                        success(res) {
                            // 清空所有缓存
                            wx.clearStorageSync()
                            wx.navigateTo({
                                url: '/pages/login/login',
                            })
                        }
                    })
                } else {
                    // 回调完成
                    resolve(res.data)
                }
            },
            fail: err => {
                reject(err)
            }
        })
    })
}